package com.hopedove.workshop.viewmodel.shiftchange

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.hopedove.net.ApiCallResult
import com.hopedove.viewmodel.BaseViewModel
import com.hopedove.viewmodel.CommonEvent
import com.hopedove.workshop.api.ShiftChangeClothInfo
import com.hopedove.workshop.api.ShiftChangeSaveItem
import com.hopedove.workshop.api.WorkshopApi
import com.hopedove.workshop.data.pojo.ObservableShiftRecordItem
import com.hopedove.workshop.repository.WorkshopUserRepository
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

class ShiftChangeRecordViewModel(
    private val api: WorkshopApi,
    private val userRepository: WorkshopUserRepository,
) : BaseViewModel() {

    val userName = MutableLiveData("记录人：${userRepository.getSignedInUserName()}")
    val machineNo = MutableLiveData("")
    val clothNo = MutableLiveData("")
    val addClothBtnEnable = MutableLiveData(false)

    // 布号信息
    private var clothInfo = mutableListOf<ShiftChangeClothInfo>()

    // 记录条目
    private var recordList = mutableListOf<ObservableShiftRecordItem>()
    private val _records = MutableLiveData<List<ObservableShiftRecordItem>>()
    val records: LiveData<List<ObservableShiftRecordItem>> = _records

    private var getClothInfoJob: Job? = null


    /**
     *  车号输入框，回车
     */
    fun onMachineNoActionDone() {
        val machine = machineNo.value!!
        if (machine.isEmpty() || getClothInfoJob?.isCompleted?.not() == true) return

        // 清空列表和布号
        clearClothNo()
        clearItems()

        getClothInfoJob = viewModelScope.launch {
            when (val result = api.shiftChangeGetClothInfo(machine)) {
                is ApiCallResult.Success -> {
                    val data = result.data!!
                    clothInfo.clear()
                    clothInfo.addAll(data)

                    setAddEmptyButtonState()
                    when {
                        clothInfo.isEmpty() -> Unit
                        clothInfo.size == 1 -> clothNo.postValue(clothInfo[0].clothNo)
                        else -> {
                            _commonEvent.value = CommonEvent("event_select_cloth_info", clothInfo)
                        }
                    }
                }
                is ApiCallResult.Error -> {
                    restoreInitialState()
                    _toastText.value = result.error
                }
            }
        }
    }

    /**
     *  选择了布号信息
     */
    fun onClothInfoSelected(index: Int) {
        clothNo.postValue(clothInfo[index].clothNo)
    }

    // 选择原料
    fun onSelectMaterialClick() {
        if (isClothNoEmpty()) {
            _toastText.value = "先录入布号"
            return
        }
        val cloth = currentCloth()!!

        // 清除之前的信息
        clearItems()

        viewModelScope.launch {
            when (val result = api.shiftChangeGetMaterials(cloth.groupNo)) {
                is ApiCallResult.Success -> {
                    val data = result.data!!

                    recordList.clear()
                    recordList += data.map { ObservableShiftRecordItem(it.info, it.id) }

                    if (data.size == 1) {
                        _records.postValue(recordList)
                    } else {
                        _commonEvent.value = CommonEvent("event_select_material", recordList)
                    }
                }
                is ApiCallResult.Error -> _toastText.value = result.error
            }
        }
    }

    /**
     *  原料选择完成
     */
    fun onMaterialSelected(indexes: List<Int>) {
        val list = recordList.filterIndexed { index, _ -> indexes.contains(index) }
        recordList.clear()
        recordList += list
        _records.postValue(recordList)
    }

    // 布号录入
    fun onAddClothClick() {
        if (isClothNoEmpty()) {
            _toastText.value = "先录入布号"
            return
        }

        // 如果没有经过筛选，_records 和 recordList 不一致，以 _records 为准
        val list = _records.value?.toMutableList() ?: mutableListOf()

        // 有空白纱织信息的条目,替换掉，否则新增
        val emptyInfoItem = list.find { it.info.isEmpty() }
        if (emptyInfoItem != null) {
            list.remove(emptyInfoItem)
        }
        list.add(ObservableShiftRecordItem("", ""))
        recordList = list
        _records.postValue(recordList)
    }

    // 直接录入
    fun onAddEmptyClick() {
        // 不用检查布号

        clearItems()
        val list = _records.value?.toMutableList() ?: mutableListOf()
        list.add(ObservableShiftRecordItem("", ""))
        recordList = list
        _records.postValue(recordList)
    }

    // 保存
    fun onSaveClick() {
        val userSession = userRepository.getSignedUserSession() ?: return

        val cloth: ShiftChangeClothInfo = if (isClothNoEmpty()) {
            // 布号为空情况下，只有车号有值
            ShiftChangeClothInfo("", "", machineNo.value!!, "")
        } else {
            currentCloth()!!
        }

        if (recordList.isEmpty()) {
            _toastText.value = "至少需要一行数据"
            return
        }

        if (recordList.any { it.shiftInfo.get().isNullOrEmpty() }) {
            _toastText.value = "交班信息不能为空"
            return
        }


        val saveList = recordList.map {
            ShiftChangeSaveItem(
                cloth.machineNo,
                cloth.clothNo,
                it.info,
                it.shiftInfo.get()!!,
                cloth.workshop,
                cloth.groupNo,
                id = it.id
            )
        }

        viewModelScope.launch {
            when (val result =
                api.shiftChangeRecordAdd(userSession.userId, userSession.userName, saveList)) {

                is ApiCallResult.Success -> {
                    _toastText.value = "保存成功!"

                    // 恢复初始状态
                    restoreInitialState()
                }

                is ApiCallResult.Error -> _toastText.value = result.error
            }
        }
    }

    private fun clearClothNo() {
        clothNo.postValue("")
        clothInfo.clear()
    }

    private fun clearItems() {
        _records.postValue(emptyList())
        recordList.clear()
    }

    // 设置【直接录入】按钮状态
    private fun setAddEmptyButtonState() {
        addClothBtnEnable.postValue(clothInfo.isEmpty())
    }

    // 布号是否为空
    private fun isClothNoEmpty(): Boolean {
        return currentCloth() == null
    }

    // 当前的布号信息
    private fun currentCloth(): ShiftChangeClothInfo? {
        return clothInfo.find { it.clothNo == clothNo.value!! }
    }

    private fun restoreInitialState() {
        machineNo.postValue("")
        clearClothNo()
        clearItems()
        addClothBtnEnable.postValue(false)
    }
}